package main.工具.解析.java;

import java.util.ArrayList;
import java.util.List;

import main.工具.公用.FileUtil;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclaration;

public class MethodExtractor {

  private static final ASTParser parser = ASTParser.newParser(AST.JLS8);

  /**
   * 
   * @param args 唯一参数为JDK源码路径。可由JDK目录下的src.zip解压。
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.out.println("需要JDK源码路径作为唯一参数");
      return;
    }
    String JDK_SRC_PATH = args[0];
    String classPath = JDK_SRC_PATH + "java/util/ArrayList.java";

    parser.setSource(FileUtil.getStringFromSourceFile(classPath).toCharArray());

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

      @Override
      public boolean visit(MethodDeclaration node) {
        List<String> parameters = new ArrayList<String>();
        for (Object parameter : node.parameters()) {
          VariableDeclaration variableDeclaration = (VariableDeclaration) parameter;
          String type =
              variableDeclaration.getStructuralProperty(SingleVariableDeclaration.TYPE_PROPERTY)
                  .toString();
          for (int i = 0; i < variableDeclaration.getExtraDimensions(); i++) {
            type += "[]";
          }
          parameters.add(type + " " + variableDeclaration.getName());
        }

        System.out.println(node.getReturnType2() + " " + node.getName() + "("
            + String.join(", ", parameters) + ")");
        return super.visit(node);
      }
    });
  }
}
